﻿using System.IO;
using NUnit.Framework;
using System;

namespace Pylor.Tests
{
    [TestFixture]
    public class AssertTest
    {
        [Test]
        public void AllRoles()
        {
            var r1 = Rules.FromString(File.ReadAllText(@"..\..\Rules-AllRoles.xml"));

            Assert.IsTrue(r1.HasPermission("RoleC", "Resource1"));
            Assert.IsFalse(r1.HasPermission("RoleA", "Resource1"));
            Assert.IsFalse(r1.HasPermission("RoleB", "Resource1"));
        }

        [Test]
        public void ExplicitAllowOnly()
        {
            var r1 = Rules.FromString(File.ReadAllText(@"..\..\Rules-ExplicitAllowOnly.xml"));

            Assert.IsTrue(r1.HasPermission("RoleA", "Resource1"));
        }

        [Test]
        public void RoleNotInAnyRule()
        {
            var r1 = Rules.FromString(File.ReadAllText(@"..\..\Rules-RoleNotInAnyRule.xml"));

            Assert.IsFalse(r1.HasPermission("RoleD", "Resource1"));
            Assert.IsFalse(r1.HasPermission("RoleD", "Resource2"));
        }

        [Test]
        public void ExplicitAllowAndDeny()
        {
            var r1 = Rules.FromString(File.ReadAllText(@"..\..\Rules-ExplicitAllowAndDeny.xml"));

            // Role tem um Allow explicito para um recurso e tb um Deny explicito
            Assert.IsFalse(r1.HasPermission("RoleA", "Resource1"));
        }

        [Test]
        public void StressTest()
        {
            // test a file with over 1000 rules

            var s1 = File.ReadAllText(@"..\..\StressRules.xml");
            var r1 = Rules.FromString(s1);

            AssertStressRules(r1); // to "warmup" the regular expressions
            var start = DateTime.Now;

            for (var i = 0; i < 1000; i++)
            {
               AssertStressRules(r1);
            }

            Console.WriteLine(DateTime.Now.Subtract(start));
        }

        private static void AssertStressRules(Rules rs)
        {
            Assert.IsTrue(rs.HasPermission("RoleA", "Artemis.Xyz.Mno.Feature1"));
            Assert.IsFalse(rs.HasPermission("RoleB", "Artemis.Xyz.Mno.Feature1"));
            Assert.IsFalse(rs.HasPermission("RoleB", "Artemis.Web.Controllers.ExceptionsController"));
            Assert.IsTrue(rs.HasPermission("RoleX", "Miguel Vitorino"));
        }
    }
}
